package 链表.倒数第K个节点;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/3/14 17:14
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        ListNode node = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4))));
        System.out.println(getKthFromEnd(node, 2).val);
    }

    public static ListNode getKthFromEnd(ListNode head, int k) {
        //获取链表的长度
        int nodeNum = 0;
        ListNode p = head;
        while (p != null){
            nodeNum++;
            p = p.next;
        }
        int target = nodeNum - k + 1;
        ListNode q = head;
        int count = 0;
        while (q != null){
            count++;
            if (count == target){
                return q;
            }
            q = q.next;
        }
        return head;
    }
}
